package model

import (
	"errors"
	"gopkg.in/mgo.v2/bson"
	"src/util/time"
)

type LostProperty struct {
	ID         bson.ObjectId `bson:"_id,omitempty" json:"id,omitempty"`
	State      int           `json:"state" bson:"state"`           //状态：0表示未领取  ，1表示已领取
	Title      string        `json:"title" bson:"title"`           //标题
	Remarks    string        `json:"remarks" bson:"remarks"`       //备注
	Imgs       []Img         `bson:"imgs" json:"imgs"`             //图片
	Method     string        `json:"method" bson:"method"`         //认领方法
	Time       string        `json:"time" bson:"time"`             //捡到时间
	Place      string        `json:"place" bson:"place"`           //捡到地点
	Recipients string        `json:"recipients" bson:"recipients"` //领取人
	IssueTime  int64         `bson:"issue_time" json:"issue_time"` //创建时间
}

type Img struct {
	URL      string `bson:"url" json:"url"`             // 图片URL
	MicroURL string `bson:"micro_url" json:"micro_url"` // 缩略图URL
}

func CreatLostProperty(Title, Remarks, Method, Time, Place string, Imgs []Img) (LostProperty, error) {
	NewLostProperty := LostProperty{
		State:      0,
		Title:      Title,
		Remarks:    Remarks,
		Imgs:       Imgs,
		Method:     Method,
		Time:       Time,
		Place:      Place,
		Recipients: "",
		IssueTime:  time.GetSecondTimestamp(),
	}
	err := insertLostProperty(NewLostProperty)
	if err != nil {
		return LostProperty{}, err
	}
	query := bson.M{
		"issue_time": NewLostProperty.IssueTime,
	}
	return findLostProperty(query, DefaultSelector)
}

func ChangeLostProperty(id string, newLostProperty LostProperty) error {
	if !bson.IsObjectIdHex(id) {
		return errors.New("id param error")
	}
	findquery := bson.M{
		"_id": bson.ObjectIdHex(id),
	}
	updataquery := bson.M{
		"$set": bson.M{
			"title":   newLostProperty.Title,
			"remarks": newLostProperty.Remarks,
			"imgs":    newLostProperty.Imgs,
			"method":  newLostProperty.Method,
			"time":    newLostProperty.Time,
			"place":   newLostProperty.Place,
		},
	}
	return updateLostProperty(findquery, updataquery)
}

func GetLostPropertyAll(page int, num int, Type int) ([]LostProperty, error) {
	var query bson.M
	if Type == 2 {
		query = bson.M{}
	} else {
		query = bson.M{
			"state": Type,
		}
	}
	fields := []string{
		"state", "-issue_time",
	}
	selector := bson.M{
		"_id":        1,
		"state":      1,
		"title":      1,
		"issue_time": 1,
		"remarks":    1,
	}
	return findLostPropertys(query, selector, page, num, fields...)
}

func GetNewLostProperty() (LostProperty, error) {
	query := bson.M{}
	fields := []string{
		"-issue_time",
	}
	newLostProperty, err := findLostPropertys(query, DefaultSelector, 1, 1, fields...)
	if len(newLostProperty) == 0 {
		return LostProperty{}, err
	}
	return newLostProperty[0], err
}

func FinishLostProperty(id string, Recipients string) error {
	if !bson.IsObjectIdHex(id) {
		return errors.New("id param error")
	}
	findquery := bson.M{
		"_id": bson.ObjectIdHex(id),
	}
	updataquery := bson.M{
		"$set": bson.M{
			"state":      1,
			"recipients": Recipients,
		},
	}
	return updateLostProperty(findquery, updataquery)
}

func DeleteLostProperty(id string) error {
	if !bson.IsObjectIdHex(id) {
		return errors.New("id param error")
	}
	return deleteLostProperty(bson.ObjectIdHex(id))
}

func GetById(id string) (LostProperty, error) {
	if !bson.IsObjectIdHex(id) {
		return LostProperty{}, errors.New("id param error")
	}
	query := bson.M{
		"_id": bson.ObjectIdHex(id),
	}
	return findLostProperty(query, DefaultSelector)
}

/*************/
func updateLostProperty(query, update interface{}) error {
	sess := globalSess.Clone()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(LostPropertyTABLE)

	return Table.Update(query, update)
}
func insertLostProperty(docs ...interface{}) error {
	sess := globalSess.Clone()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(LostPropertyTABLE)

	return Table.Insert(docs...)
}
func findLostProperty(query, selector interface{}) (LostProperty, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(LostPropertyTABLE)

	LostProperty := LostProperty{}
	err := Table.Find(query).Select(selector).One(&LostProperty)
	return LostProperty, err
}

func findLostPropertyNum(query interface{}) (int, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(LostPropertyTABLE)

	return Table.Find(query).Count()
}
func findLostPropertys(query, selector interface{}, page, perPage int, fields ...string) ([]LostProperty, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(LostPropertyTABLE)

	LostPropertys := []LostProperty{}
	err := Table.Find(query).Select(selector).Sort(fields...).Skip((page - 1) * perPage).Limit(perPage).All(&LostPropertys)
	return LostPropertys, err
}
func findLostPropertyALL(query interface{}) ([]LostProperty, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(LostPropertyTABLE)
	fields := []string{
		"-issue_time",
	}
	LostPropertys := []LostProperty{}
	err := Table.Find(query).Sort(fields...).All(&LostPropertys)
	return LostPropertys, err
}
func deleteLostProperty(id bson.ObjectId) error {
	sess := globalSess.Clone()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(LostPropertyTABLE)
	return Table.RemoveId(id)
}
